import logging
import time

from constants.constant import EXCEL_PATH, ERR_APP_EXCEL_PATH, URL_MY_PROJECT
from model.Config import Config
from operators.AGCConnect import loginAgcConnect, isExistProject, createProject, directToCreatePage, getAppId, \
    downloadProfile, createApp, logout, addFingerprint, addGameInfo, saveProperties, addProfile, checkAndChangeSubject, deleteApp
from operators.DevelopPlat import loginDevelop, directToCashFlow, addAdPos, getAdPos, devPlatLogout, addMedia
from utils.FileUtil import processExcel, genErrExcel, save_review_excel, deleteOldDir

logging.basicConfig(
    filename="log.txt",
    filemode='w',
    format="%(asctime)s - %(levelname)s - %(message)s",
    level= logging.INFO
)

def getBaseSetting(excelPath):
    userConfig = Config().getUserConfig()
    runConfig = Config().getRunConfig()
    if userConfig["user_name"] == "" or userConfig["user_password"] == "":
        logging.error("请在Config/config.json中设置账户和密码")
        return None

    try:
        appInfos = processExcel(excelPath)
    except Exception:
        logging.error("请确认config/appInfos.xlsx文件存在")
        return None

    return appInfos, userConfig, runConfig


def deleteAppAndRetryCreateAppProfileAndIdMapping(appInfo, userConfig, runConfig):
    webdriver = None
    try:
        webdriver = loginAgcConnect(appInfo, userConfig)
        if webdriver is None:
            return

        if not runConfig["isTest"]:
            checkAndChangeSubject(webdriver, appInfo)

        # 如果不存在项目，直接重走 ,存在：则删除了再创建app
        projectExistFlag = isExistProject(webdriver, appInfo)
        if not projectExistFlag:
            createProject(webdriver, appInfo)
        else :
            deleteApp(webdriver, appInfo)
            projectExistFlag = False

        directToCreatePage(webdriver, appInfo, projectExistFlag)

        createApp(webdriver, appInfo)

        appInfo.app_id = getAppId(webdriver, appInfo)

        addProfile(webdriver, appInfo, "agc_debug")

        addProfile(webdriver, appInfo, "agc_release")

        downloadProfile(webdriver, appInfo, "agc_debug")

        downloadProfile(webdriver, appInfo, "agc_release")

        webdriver.get(URL_MY_PROJECT)
        time.sleep(5)

        addFingerprint(webdriver, appInfo)

        addGameInfo(webdriver, appInfo)




    except Exception:
        raise
    finally:
        if webdriver is not None:
            logout(webdriver)
            time.sleep(10)
            webdriver.quit()


def createAppAndProfileAndMapping(appInfo, userConfig, runConfig):
    webdriver = None
    try:
        webdriver = loginAgcConnect(appInfo, userConfig)
        if webdriver is None:
            return

        if not runConfig["isTest"]:
            checkAndChangeSubject(webdriver, appInfo)

        projectExistFlag = isExistProject(webdriver, appInfo)
        if not projectExistFlag:
            createProject(webdriver, appInfo)

        directToCreatePage(webdriver, appInfo, projectExistFlag)

        createApp(webdriver, appInfo)

        appInfo.app_id = getAppId(webdriver, appInfo)


        addProfile(webdriver, appInfo, "agc_debug")

        addProfile(webdriver, appInfo, "agc_release")

        downloadProfile(webdriver, appInfo, "agc_debug")

        downloadProfile(webdriver, appInfo, "agc_release")

        webdriver.get(URL_MY_PROJECT)
        time.sleep(5)

        addFingerprint(webdriver, appInfo)

        addGameInfo(webdriver, appInfo)

    except Exception:
        raise
    finally:
        if webdriver is not None:
            logout(webdriver)
            time.sleep(10)
            webdriver.quit()


def getAdInfo(appInfo, userConfig):
    webdriver = None
    try:
        webdriver = loginDevelop(appInfo, userConfig)
        if webdriver is None:
            return

        directToCashFlow(webdriver, appInfo)

        addMedia(webdriver, appInfo)

        addAdPos(webdriver, appInfo)

        getAdPos(webdriver, appInfo)
    except Exception:
        raise
    finally:
        if webdriver is not None:
            devPlatLogout(webdriver)
            time.sleep(10)
            webdriver.quit()

def firstCreate():
    appInfos, userConfig, runConfig = getBaseSetting(EXCEL_PATH)
    errNameList = []
    appInfoList = []
    for appInfo in appInfos:
        try:
            # 创建app和Id映射
            if runConfig["isCreateAppAndProfile"]:
                createAppAndProfileAndMapping(appInfo, userConfig, runConfig)

            # 获取广告信息
            if runConfig["isGetAdInfo"]:
                getAdInfo(appInfo, userConfig)

            # 保存properties
            saveProperties(appInfo, userConfig)

        except Exception as e:
            logging.error(e)
            errNameList.append(appInfo.app_name)
            appInfoList.append(appInfo)
            continue
    genErrExcel(errNameList)

def retryErrList():
    logging.info("---------------")
    logging.info("开始重试失败的项目")
    logging.info("---------------")
    appInfos, userConfig, runConfig = getBaseSetting(ERR_APP_EXCEL_PATH)
    errNameList = []
    for appInfo in appInfos:
        try:
            # 删除原有文件夹:全流程ok，直接返回
            if not deleteOldDir(appInfo,userConfig):
                return

            # 删除再创建app和id映射
            if runConfig["isCreateAppAndProfile"]:
                deleteAppAndRetryCreateAppProfileAndIdMapping(appInfo, userConfig,runConfig)

            # 获取广告信息
            if runConfig["isGetAdInfo"]:
                getAdInfo(appInfo, userConfig)

            # 保存properties
            saveProperties(appInfo,userConfig)

        except Exception as e:
            logging.error(e)
            errNameList.append(appInfo.app_name)
            continue
    genErrExcel(errNameList)

def main():
    firstCreate()

    retryErrList()

if __name__  == "__main__":
    main()